package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.BankInfo;
import com.eeepay.eeepay_v2.model.IntoPiecesInfo;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.util.StatuUtils;
import com.eeepay.eeepay_v2.view.AreaSelectView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABAppUtil;
import com.eeepay.v2_library.util.ABRegUtil;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.LeftRightText;
import com.eeepay.v2_library.view.TitleBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerAddModular;
import cn.eeepay.api.grpc.nano.MerAddServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/11.
 * 结算信息
 */
public class SettlementActivity extends ABBaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, TitleBar.LeftBtnOnClickListener, View.OnFocusChangeListener {

    //开户名、开户账号、开户行名称、联行行号
    private LabelEditText nameLet, noLet;
    private LeftRightText bankLrt, areaLrt, branchLrt;
    private RadioGroup radioGroup;
    private Button nextBtn;
    private TitleBar titleBar;
    private TextView cnoQueryTv;
    private AreaSelectView areaPopView;

    private final int ACCOUNT = 0, BASE = 1, BRANCH = 2;
    private String accountType, accountName, accountNo, bankName,
            branch, cnapsNo, city, zhAddress, status = "未完成";
    private IntoPiecesInfo intoPieces;
    private List<BankInfo> bankList;
    private Bundle mBundle;
    private BankInfo bankInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_settlement;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.tb_settlement);
        nameLet = getViewById(R.id.let_settle_account_name);
        noLet = getViewById(R.id.let_settle_account_number);
        bankLrt = getViewById(R.id.lrt_settle_account_bank);
//        cnapsNoLet = getViewById(R.id.let_settle_united_bank_number);
        areaLrt = getViewById(R.id.lrt_settle_account_area);
        branchLrt = getViewById(R.id.lrt_settle_account_zh);
        nextBtn = getViewById(R.id.btn_settle_next);
        cnoQueryTv = getViewById(R.id.tv_settle_united_bank_query);

        radioGroup = getViewById(R.id.rgp_into_account_type);
//        noLet.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
//        cnapsNoLet.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
    }

    @Override
    protected void eventOnClick() {

        titleBar.setLeftOnClickListener(this);
        radioGroup.setOnCheckedChangeListener(this);
        radioGroup.getChildAt(0).performClick();
        nextBtn.setOnClickListener(this);
        cnoQueryTv.setOnClickListener(this);
        areaLrt.setOnClickListener(this);
        branchLrt.setOnClickListener(this);
        bankLrt.setOnClickListener(this);
        areaLrt.setRightText(zhAddress);

        noLet.getEditText().setOnFocusChangeListener(this);

        areaPopView = new AreaSelectView(mContext);
        //选择地区完成回调
        areaPopView.setOnAreaSelectedListener(new AreaSelectView.OnAreaSelectedListener() {
            @Override
            public void onSelected(String area) {
                zhAddress = area;
                areaLrt.setRightTextColor(area, R.color.titlebar_title_txt_color);
                areaPopView.dismiss();
                String cityStr = areaPopView.getCitySelected();
                city = cityStr.substring(0, cityStr.length() - 1);
                Log.d("bank", " 城市: " + city);
//                if (!TextUtils.isEmpty(noLet.getEditContent())) {
//                    accountNo = noLet.getEditContent();
//                    if (TextUtils.isEmpty(accountNo))
//                        return;
//                    sendHttpRequest(BRANCH);
//                }
            }
        });

//        CheckUtils.addEditChangeListener(nextBtn, R.drawable.icon_next_step, R.drawable.icon_no_next_step, nameLet, noLet);

        intoPieces = SPUtils.getIntoPieces();
        if (intoPieces != null) {
            accountType = intoPieces.getAccountType();
            if (accountType != null) {
                if ("对私".equals(accountType)) {
                    radioGroup.getChildAt(0).performClick();
                } else if ("对公".equals(accountType)) {
                    radioGroup.getChildAt(1).performClick();
                }
            } else {
                accountType = "对私";
            }
            nameLet.setEditContent(intoPieces.getAccountName());
            noLet.setEditContent(intoPieces.getAccountNo());
            bankLrt.setRightText(intoPieces.getBankName());
            cnapsNo = intoPieces.getCnapsNo();
            areaLrt.setRightText(intoPieces.getZhAddress());
//            cnapsNoLet.setEditContent(intoPieces.getCnapsNo());
            branchLrt.setRightText(intoPieces.getZh());
        }
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        MerAddServiceGrpc.MerAddServiceBlockingStub stub = MerAddServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(5, TimeUnit.SECONDS);
                        switch (taskId) {
                            case ACCOUNT:
                                MerAddModular.AccountNoReq accReq = new MerAddModular.AccountNoReq();
                                accReq.settleAccountNo = accountNo;
                                return stub.checkSettleAccountNo(accReq);
                            case BRANCH:
                                MerAddModular.BankAndCnapReq bankReq = new MerAddModular.BankAndCnapReq();
                                bankReq.accountNo = accountNo;
                                bankReq.cityName = city;
                                return stub.getBankAndCnap(bankReq);
                            case BASE:
                                MerAddModular.BaseInfoReq baseReq = new MerAddModular.BaseInfoReq();
                                baseReq.accountName = accountName;
                                baseReq.accountNo = accountNo;
                                baseReq.idCardNo = intoPieces.getIdCardNo();
                                baseReq.mobilephone = intoPieces.getMerPhone();
                                baseReq.teamId = ConfigPorperties.getInstance().getTeamId();
                                //add by zhuangzeqin 2017年4月19日15:57:24  增加参数pbid
                                baseReq.bpId = intoPieces.getProId();
                                return stub.baseInfoCheck(baseReq);
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (result == null) {
                            showToast("查询失败");
                            return;
                        }
                        switch (taskId) {
                            case ACCOUNT:/**校验结算卡获取开户行**/
                                MerAddModular.BankNameRes bankNameRes = (MerAddModular.BankNameRes) result;
                                if (!bankNameRes.resMsg.status) {
                                    showToast(bankNameRes.resMsg.msg);
                                } else {
                                    bankName = bankNameRes.bankName;
                                    bankLrt.setRightText(bankName);
                                }
                                break;
                            case BRANCH:/**获取支行信息**/
                                MerAddModular.BankAndCnapRes bankCnapRes = (MerAddModular.BankAndCnapRes) result;
                                if (bankList != null && bankList.size() > 0)
                                    bankList.clear();
                                if (!bankCnapRes.resMsg.status) {//查询失败
                                    showToast(bankCnapRes.resMsg.msg);
                                } else {
                                    MerAddModular.CnapInfo[] cnapInfo = bankCnapRes.cnapInfo;
                                    BankInfo bankInfo;
                                    bankList = new ArrayList<BankInfo>();
                                    for (MerAddModular.CnapInfo cnap : cnapInfo) {
                                        bankInfo = new BankInfo(cnap.bankName, cnap.cnapsNo);
                                        bankList.add(bankInfo);
                                    }
                                    if (bankList != null && bankList.size() > 0) {
                                        mBundle = new Bundle();
                                        mBundle.putSerializable(Constant.KEY_LIST,
                                                (Serializable) bankList);
                                        goActivityForResult(SelectBankActivity.class, mBundle, Constant.RESULTCODE_100);
                                    }
                                }
                                break;
                            case BASE:/**校验三码(开户名,身份证,结算卡号)认证**/
                                MerAddModular.BaseInfoRes baseInfoRes = (MerAddModular.BaseInfoRes) result;
                                if (!baseInfoRes.resMsg.status) {
                                    showToast(baseInfoRes.resMsg.msg);
                                } else {
                                    goActivity(ServiceRateActivity.class);
//                                    ScreenSwitch.switchActivity(SettlementActivity.this, ServiceRateActivity.class, null, 0);
                                    getCurrentValue();
                                    finish();
                                }
                                break;
                        }
                    }
                });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_bis_public:
                accountType = "对私";
                break;
            case R.id.rbtn_person_private:
                accountType = "对公";
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lrt_settle_account_bank:
                accountNo = noLet.getEditContent();
                if (!TextUtils.isEmpty(accountNo))
                    sendHttpRequest(ACCOUNT);
                break;
            case R.id.lrt_settle_account_area://开户地区选择
                if (!TextUtils.isEmpty(accountNo)) {
                    onFocusChange(null, false);
                }
                showPopWindow();
                break;
            case R.id.lrt_settle_account_zh://支行
                Log.d("branch", "支行");
                accountNo = noLet.getEditContent();
                if (TextUtils.isEmpty(accountNo) || TextUtils.isEmpty(city)) {
                    showToast("请填写正确的银行卡号和开户行地区");
                    return;
                }
                sendHttpRequest(BRANCH);
                sendHttpRequest(ACCOUNT);
                break;
            case R.id.tv_settle_united_bank_query://联行行号查询
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TITLE, "联行行号查询");
                bundle.putString(Constant.INTENT_FLAG, Constant.CANPS_QUERY);
                bundle.putString(Constant.CANPS_QUERY, Constant.URL.CANPS_QUERY);
                goActivity(WebViewActivity.class, bundle);
                break;
            case R.id.btn_settle_next:
//                if (!CardTools.getInstance().isBankCardNo(accountNo)) {
//                    showToast("请输入有效的银行卡号");
//                    return;
//                }
//                if (!CardTools.getInstance().isBankCardNo(cnapsNo)) {
//                    showToast("请输入正确的联行行号");
//                    return;
//                }
                accountName = nameLet.getEditContent().trim();
                if (TextUtils.isEmpty(accountName) ||
                        !ABRegUtil.isRegiest(accountName, Constant.NAME_REGEX)) {
                    showToast("请填写有效的用户名");
                    return;
                }
                if (TextUtils.isEmpty(intoPieces.getIdCardNo())) {
                    showToast("身份证未填写，请先在基本信息界面填写");
                    return;
                }

                boolean complete = checkStatus();
                if (!complete) {
                    showToast("资料填写不完整");
                } else {
                    sendHttpRequest(BASE);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        bankInfo = (BankInfo) data.getSerializableExtra(Constant.TAG);
        if (bankInfo != null) {
            branch = bankInfo.getBank_name();
            branchLrt.setRightTextColor(branch, R.color.gray_text_color);
            cnapsNo = bankInfo.getCnaps_no();
        }
    }

    private void showPopWindow() {
        ABAppUtil.hideSoftInput(this);
        if (areaPopView == null) {
            areaPopView = new AreaSelectView(mContext);
        }
        areaPopView.showAtLocation(areaLrt, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 根据城市和银行卡号获取对应支行
     */
    private void getBranch() {
        accountNo = noLet.getEditContent().trim();
        if (TextUtils.isEmpty(accountNo))
            return;
//        if (bankList == null || bankList.size() == 0) {
        sendHttpRequest(BRANCH);
//        }
    }

    /**
     * 保存数据
     */
    public void getCurrentValue() {
//        cnapsNo = cnapsNoLet.getEditContent();
//        if (!isBack) {
//            Log.d("check", "银行卡: " + CardTools.getInstance().isBankCardNo(accountNo));
//            if (CardTools.getInstance().isBankCardNo(accountNo)) {
//                showToast("请输入正确的银行卡号");
//                return;
//            }
//            Log.d("check", "结算卡: " + CardTools.getInstance().isBankCardNo(cnapsNo));
//            if (CardTools.getInstance().isBankCardNo(cnapsNo)) {
//                showToast("请输入正确的联行行号");
//                return;
//            }
//        }
        accountNo = noLet.getEditContent().trim();
        accountName = nameLet.getEditContent().trim();
        bankName = bankLrt.getRighText();
        zhAddress = areaLrt.getRighText();
        branch = branchLrt.getRighText();

        if (intoPieces != null) {
            intoPieces.setAccountName(accountName);
            intoPieces.setAccountNo(accountNo);
            intoPieces.setBankName(bankName);
            intoPieces.setCnapsNo(cnapsNo);
            intoPieces.setAccountType(accountType);
            intoPieces.setZhAddress(zhAddress);
            intoPieces.setZh(branch);
            SPUtils.saveIntoPieces(intoPieces);
        }
    }

    private boolean checkStatus() {
        boolean flag = false;
        accountNo = noLet.getEditContent().trim();
        accountName = nameLet.getEditContent().trim();
        bankName = bankLrt.getRighText();
        if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountNo)
                && !TextUtils.isEmpty(bankName) && !TextUtils.isEmpty(cnapsNo)) {
            status = "已完成";
            flag = true;
        } else {
            status = "未完成";
            flag = false;
        }
        StatuUtils.getInstance().setSettlement(status);
        Intent intent = new Intent();
        intent.putExtra("status", status);
        setResult(RESULT_OK, intent);
        return flag;
    }

    @Override
    public void onLeftClick(View view) {
        getCurrentValue();
        checkStatus();
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            onLeftClick(null);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {//失去焦点时校验
            accountNo = noLet.getEditContent();
            if (TextUtils.isEmpty(accountNo)) {
//                showToast("请填写正确的银行卡号");
                return;
            }
            sendHttpRequest(ACCOUNT);
        }
    }
}
